
Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

var record_start = 0; 

var sm = new Ext.grid.CheckboxSelectionModel();
var cm=new Ext.grid.ColumnModel([ 
sm,
new Ext.grid.RowNumberer({header: "编号",
width:40, 
renderer:function(value,metadata,record,rowIndex){ 
return record_start + 1 + rowIndex; 
} 
}),
{header:'信用评级',dataIndex:'confirmPdlevel',width:100,sortable:true}, 
{header:'评级流水号',dataIndex:'serialNo',width:120, hidden:true},
{header:'信用评级生成日期',dataIndex:'confirmDate',width:120,sortable:true},
{header:'PD值',dataIndex:'confirmPdvalue',width:100,sortable:true},
{header:'评级到期日',dataIndex:'endDate',width:100,sortable:true},
{header:'财报会计月份',dataIndex:'reportDate',width:100,sortable:true},
{header:'打分卡模型',dataIndex:'modelId',width:100,sortable:true},
{header:'初评人',dataIndex:'firstUserId',width:100,sortable:true},
{header:'初评机构',dataIndex:'firstOrgId',width:100,sortable:true},
{header:'评级状态',dataIndex:'phaseStat',width:120,sortable:true},
]); 
var ds=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'rating/listHistoryPD.do',
method:'POST'
}), 
reader:new Ext.data.JsonReader({ 
totalProperty:'total',  
root:'resultData'},[
{name:'serialNo'}, 
{name:'confirmDate'}, 
{name:'confirmPdlevel'}, 
{name:'endDate'}, 
{name:'modelId'},  
{name:'reportDate'},  
{name:'firstUserId'},  
{name:'firstOrgId'},  
{name:'confirmPdvalue'},
{name:'phaseStat'}
]) 
}); 

var modelStore=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'showPDModelList.do?custType='+document.getElementById('custTypeNo').innerHTML,
method:'GET'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'name'}, 
{name:'code'}
]) 
});
modelStore.load();

var reportDateStore=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'rating/showReportDate.do',
	method:'GET'
	}), 
	reader:new Ext.data.JsonReader({ },[
	{name:'name'}, 
	{name:'code'}
	]) ,
	autoLoad: true
	}); 

var grid=new Ext.grid.GridPanel({ 
id:'myCustomers',
renderTo:"rating_list", 
stripeRows:true,//斑马线效果
title:"历史评级信息", 
height:500, 
cm:cm,
store: ds, 
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },   
            bbar: new Ext.PagingToolbar({   
                pageSize: 20,   
                store: ds,   
                displayInfo: true,   
                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
                emptyMsg: "没有数据" ,
                doLoad : function(start){ 
   record_start = start; 
var o = {}, pn = this.getParams(); 
          o[pn.start] = start; 
          o[pn.limit] = this.pageSize; 
this.store.load({params:o}); 
     }  
            }),
 tbar: [
 {text:'发起评级',handler: startPD},
 '-',
 {text:'评级详情',handler: PDDetail},
 '-',
 {text:'删除',handler:deletePD},
 ]              
});
ds.load({params:{start:0,limit:20}}); 


//新增客户表单
addForm = new Ext.form.FormPanel({ 
id: 'addForm', 
width: 480, 
height: 160, 
//样式 
bodyStyle: 'margin:auto;padding:auto;', 
frame: true, 
xtype: 'filedset', 
labelWidth: 100, 
items: 
[ { xtype: 'fieldset',  
collapsible: true, 
autoHeight: true, 
autoWidth: true, 
items: 
[ 
{ layout : "form",
           items : [{
        	   xtype: 'combo', 
        	   id : "modelId",
              store :modelStore,
              fieldLabel: '打分卡模板',
              valueField : 'code',
              displayField : 'name',
              emptyText : '请选择打分卡模板...',
              editable: false,
              allowBlank: false,
              blankText: '请选择打分卡模板',
              typeAhead : true,
              width: 300,
              mode:'remote',  
              triggerAction : 'all',
              selectOnFocus : true,
              hiddenName:'modelId',
              listeners:{
        	   select : function(combo, record,index){
					if(combo.lastSelectionText.indexOf('零售客户') > 0 || combo.lastSelectionText.indexOf('小水电') > 0 ||combo.lastSelectionText.indexOf('房地产') > 0 || combo.lastSelectionText.indexOf('金融') > 0){
						Ext.getCmp('reportDate').disable();
						Ext.getCmp('reportDate').hide();
					}
					else{
						Ext.getCmp('reportDate').enable();
						Ext.getCmp('reportDate').show();
					}
				}
           	}
}]},
 { layout : "form",
           items : [{
			xtype: 'combo',
			id: 'exposureTypeCombo',
			//name: 'exposureType', 
			fieldLabel: '风险暴露类型', 
			store:new Ext.data.SimpleStore({fields:['id', 'text'],data:[[]]}), 
			displayField: 'text',
			valueField: 'id',
			hiddenName: 'exposureType',
            editable:false, 
            allowBlank: false,
            blankText: '请选择风险暴露类型',
            mode: 'local', 
            triggerAction:'all', 
            frame:true,
            border:true,
            width:300,
            tpl: '<div id="treePanel" style="height:140px;width:300px;"></div>', //html代码           
            //autoWidth:true,
            //autoHeight:true, 
            emptyText:'请选择风险暴露类型...',
            resizable:true
}]},
{ layout : "form",
    items : [{
 	   xtype: 'combo', 
 	   id : "reportDate",
       store :reportDateStore,
       fieldLabel: '财报日期',
       valueField : 'code',
       displayField : 'name',
       emptyText : '请选择财报日期...',
       editable: false,
       typeAhead : true,
       allowBlank: false,
       blankText: '请选择财报日期（若列表无数据显示，表明该客户无年报数据，无法进行评级）',
       width: 300,
       mode:'remote',  
       triggerAction : 'all',
       selectOnFocus : true,
       hiddenName:'reportDate'
}]},

]}]});

var tree = new Ext.tree.TreePanel
        ({ 
            animate:true,
            titleCollapse:true,
            root:root,
            singleExpand:false,
            iconCls:"icon-tree",
            autoLoad:false,
            allowDomMove:true,
            frame:true,
            collapsible:false,
            collapsed:false,
            collapseFirst:true,
            border:false,
            listeners:{ 
            	render:function(tree){ 
            		tree.el.on('click',function(e){ 
					e.stopPropagation(); }) ;
				} 
			} 
});

var loader=new Ext.tree.TreeLoader({dataUrl:'showExposureType.do'});

var root=new Ext.tree.AsyncTreeNode
        ({
         id:"0", 
         leaf:false,
         loader: loader,
         text:"风险暴露类型",
         expandable:true,
         expanded:true 
     });         

tree.setRootNode(root);

var comboTree =  Ext.getCmp('exposureTypeCombo');      

comboTree.on('expand',function(){tree.render('treePanel');});

var tree_click = function(node,e)
        {
            if(node.attributes.leaf)
            {
                if(node.isLeaf())
                {
                    e.stopEvent();   //非叶子节点则不触发
                    comboTree.setValue(node.id);  //设置option值
                    comboTree.setRawValue(node.text);
                    //comboTree.hiddenField.value = node.id;  
                	comboTree.collapse();   //隐藏option列表
                	//alert(comboTree.value);
                	//alert(comboTree.getValue());
                	//alert(comboTree.getRawValue());
                	//alert(comboTree.value);
                }
               
            }
        };
tree.on("click",tree_click);  

//新增用户窗口 
addWin = new Ext.Window({ 
id: 'addWin', 
title: '发起评级', 
width: 500, 
height: 200, 
//背景遮罩 
modal: true, 
//重置大小 
resizable: false, 
//当关闭按钮被点击时执行的动作 
closeAction: 'hide', 
plain: true, 
buttonAlign: 'right', 
items:addForm, 
buttons: 
[  
{ text: '保存', id: 'btnSubmit' } ,
{ text: '关闭', handler: function() { Ext.getCmp('addWin').hide(); } }

] 
});

function startPD(){
	//var addForm = Ext.getCmp('addForm');
	//addForm.getForm().getEl().dom.reset(); 
	
	
	//alert("111");
	Ext.Ajax.request({
		  url:'rating/findNewestPD.do',
		  method:'POST',
		  success:function(response){
			  var addJSON = Ext.util.JSON.decode(response.responseText);
			//  alert(addJSON);
			  
			  if(addJSON==null){
				  Ext.getCmp("addWin").buttons[0].handler = addFunction; 
				  Ext.getCmp("addWin").show();
			  }else{
				  var phaseStat = addJSON.phaseStat;
					  //alert(phaseStat);
					  
					  if(phaseStat == null || phaseStat=="00" || phaseStat=="01" || phaseStat=="06" || phaseStat=="07"){
						  Ext.getCmp("addWin").buttons[0].handler = addFunction; 
						  Ext.getCmp("addWin").show();
					  }else{
						  Ext.Msg.alert("提示", "当前有评级正在进行中！<br/>请在该评级结束或退回时重新发起！"); 
					  }
			  }  
		  },failure:function(){
		    Ext.MessageBox.alert("请求异常！");
		  }
	});   
	
	
	

	//alert("链接跳转");
	//window.location.href="view/rating/CustomerRating_RatingProcess.jsp";
}

function addFunction() {

	if(addForm.form.isValid()){
			//alert("start Pd");
	
			var addPDForm=addForm.getForm().getEl().dom;
			addPDForm.action = 'rating/addPD.do';
			addPDForm.method = 'POST';
			addPDForm.submit();

//			 addForm.form.doAction('submit', { 
//
//                    url : 'rating/addPD.do', 
// 
//                    method : 'post', 
// 
//                       
//                       success : function() { 
//							
//                       
//                       
// 
//                       }, 
//                        failure : function(form, action) { 
//
//                          
// 
//                        } 
//                    }); 
	  
    }
    
}
//删除评级
function deletePD(){
var grid = Ext.getCmp('myCustomers'); 
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要删除的条目"); 
} 
else{
Ext.MessageBox.confirm('提示', '确定删除？（超级权限）', deleteConfirm);
}
}

function deleteConfirm(btn){
if (btn == 'yes') {
 Ext.Ajax.request({
  url:'rating/deletePD.do',
  params : {SerialNo : grid.getSelectionModel().getSelections()[0].data.serialNo},
  method:'POST',
  success:function(response){
   Ext.MessageBox.alert("提示","删除成功！");
   Ext.getCmp('myCustomers').store.reload(); 
  },failure:function(){
    Ext.MessageBox.alert("提示", "删除失败！"); 
  }
});
}
}

function PDDetail(){
	if (grid.getSelectionModel().getSelections()[0] == undefined) { 
		Ext.Msg.alert("提示", "请选中要操作的项！"); 
	}
	else{
		var selectedSerialNo = grid.getSelectionModel().getSelections()[0].data.serialNo;
		//alert(selectedSerialNo);
		//window.location.href="rating/showHistoryPDList.do?custId="+selectedCustId;
		window.location.href="rating/showPDDetail.do?serialNo="+selectedSerialNo;
	}
}


function rowdblclickFn(grid, rowIndex, e){//双击事件  
             var row = grid.getStore().getAt(rowIndex); 
             var selectedCustId = row.get("serialNo");
             Ext.Ajax.request({
				  url:'checkRequest.do',
				  method:'GET',
				  success:function(){
				  window.location.href="rating/showPDDetail.do?serialNo="+selectedCustId;
				  },failure:function(){
				    Ext.MessageBox.alert("请求异常！");
				  }
				});  
			}   
grid.addListener('rowdblclick',rowdblclickFn);
}); 